package com.easyim.imserver.handler.cmd;

import com.easyim.common.message.Immessage;
import com.easyim.imserver.handler.message.Handler;
import com.easyim.imserver.service.ITokenService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.easyim.imserver.constant.CacheKey.*;

@Component
@Slf4j
public class DisConnectHandler implements Handler {

    @Autowired
    @Qualifier("channelMap")
    Map<String, Map<String, Channel>>  localSession;

    @Value("${com.easyim.run.model.clusterable}")
    private Boolean cluster;

    @Override
    public String dealType() {
        return Immessage.CmdMessage.CommandType.DISCONNECT.name();
    }

    /**
     * 断开链接的请求 用户下线
     * @param channel
     * @param imMessage
     */
    @Override
    public void handlerMsg(Channel channel, Immessage.ImMessage imMessage) {
        Immessage.CmdMessage cmdMessage = imMessage.getCmdMessage();
        String device = cmdMessage.getDevice();
        String username = cmdMessage.getUsername();
        log.info("user:{} disconnect tcp connect.. ", username);
        //从本地的map将链接剔除
        localSession.get(username).remove(device);
        channel.close();
        if(cluster){
            //todo 清理redis中的会话
        }
        //todo 发送用户下线通知
    }
}
